package com.sander.guardmanagement.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.DynamicLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.sander.guardmanagement.R;
import com.sander.guardmanagement.http.BaseCallback;
import com.sander.guardmanagement.http.HomeDeleteUserHome;
import com.sander.guardmanagement.http.HomeGetUserHomelist;
import com.sander.guardmanagement.http.HttpApi;
import com.sander.guardmanagement.http.OkHttpHelper;
import com.sander.guardmanagement.response.ResponseHomeGetUserHomeList;
import com.sander.guardmanagement.response.ResponseHomeGetUserHomeListData;
import com.sander.guardmanagement.response.ResponseModel;
import com.sander.guardmanagement.response.ResponseUserLoginData;
import com.sander.guardmanagement.until.DensityUtil;
import com.sander.guardmanagement.until.UserInfoManager;
import com.sander.guardmanagement.widgets.OneTimeAlertDialog;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.util.ArrayList;
import java.util.List;

import mehdi.sakout.dynamicbox.DynamicBox;

public class MyAdressListActivity extends AppCompatActivity {


    public List<ResponseHomeGetUserHomeListData> homeList = new ArrayList<>();

    public AdressAdapter adressAdapter;

    DynamicBox loadingBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_adress_list);

        initCallBack();

        initData();

        initView();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);


    }

    private void initCallBack(){
        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.callbackLayout);
        frameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    public void initData(){
        HomeGetUserHomelist homeGetUserHomelist = new HomeGetUserHomelist();
        if (UserInfoManager.sharedManager().userInfo != null){
            ResponseUserLoginData userLoginData = UserInfoManager.sharedManager().getUserInfo();
            homeGetUserHomelist.uid = userLoginData.getId() + "";
            OkHttpHelper.getinstance().post(HttpApi.getAPiUrl(HttpApi.Home_get_user_homelist), homeGetUserHomelist.getValueOfClas(), new BaseCallback<ResponseHomeGetUserHomeList>() {
                @Override
                public void onRequestBefore() {

                }

                @Override
                public void onFailure(Request request, Exception e) {

                }

                @Override
                public void onSuccess(Response response, ResponseHomeGetUserHomeList o) {
                    if (o.getCode() == 0){
                        Log.d("sander"," => " + o.getMsg());

                        List<ResponseHomeGetUserHomeListData> homeListData = o.getData();

                        homeList = homeListData;

                        updateAdressList();

                    }else{
                        Log.d("sander"," => " + o.getMsg());
                    }

                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {

                }
            });
        }
    }

    private void initView(){
        ListView listView = (ListView)findViewById(R.id.adress_listview);
        adressAdapter = new AdressAdapter();
        listView.setAdapter(adressAdapter);

        Button action_new_adress = (Button)findViewById(R.id.new_adress_button);
        action_new_adress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNewAdressAction();
            }
        });

    }

    public void updateAdressList(){
        adressAdapter.notifyDataSetChanged();
    }

    private void onNewAdressAction(){
        Log.d("sander","new add adress ");

        Intent intent = new Intent(MyAdressListActivity.this,CityListActivity.class);
        startActivity(intent);
    }

    public void deletedCity(final int postion){
        HomeDeleteUserHome deleteUserHome = new HomeDeleteUserHome();
        ResponseHomeGetUserHomeListData data  = homeList.get(postion);
        ResponseUserLoginData userLoginData = UserInfoManager.sharedManager().getUserInfo();
        deleteUserHome.uid = userLoginData.getId() + "";
        deleteUserHome.home_id = data.id + "";
        if (data.type == 1) deleteUserHome.op_type = "0"; // 业主自己删除自己的
        if (data.type == 2) deleteUserHome.op_type = "2"; // 在这里出现2 用户本身就是租客，删除租客的地址
        if (data.type == 3 || data.type == 4) deleteUserHome.op_type = "3"; //在这里出现3，4， 只能说明，这个哥们是个住户，自己删除自己的人

        OkHttpHelper.getinstance().post(deleteUserHome.requestUrl(), deleteUserHome.getValueOfClas(), new BaseCallback<ResponseModel>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {
                    e.printStackTrace();
            }

            @Override
            public void onSuccess(Response response, ResponseModel o) {
                Log.d("sander","delete --> " + o.getMsg());
                if (o.getCode() == 0){
                    homeList.remove(postion);
                    updateAdressList();
                }else{
                    showToastMessage(o.getMsg());
                }

            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });

    }

    public void showAlertView(final int postion)
    {
        new MaterialDialog.Builder(this)
                .title("提示")
                .content("确定删除吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                        deletedCity(postion);
                    }
                })
                .show();

        Log.d("sander","确定删除了吧");

    }

    public void showToastMessage(String message){
        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();

    }
    private adressClickListener mlistener = new adressClickListener() {
        @Override
        public void onClickAdress(int position, View view) {
            Log.d("sander","入住人管理" + position);

            ResponseHomeGetUserHomeListData data  = homeList.get(position);

            Intent intent = new Intent(MyAdressListActivity.this,OccupantManagementActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("ruzhuren",data);
            intent.putExtras(bundle);
            startActivity(intent);

        }
    };
    private zhukeManagerClick managerClick = new zhukeManagerClick() {
        @Override
        public void onclickManager(int position, View view) {
            Log.d("sander","租客管理 " + position);
            ResponseHomeGetUserHomeListData data  = homeList.get(position);

            Intent intent = new Intent(MyAdressListActivity.this,TenantManagementActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("ruzhuren",data);
            intent.putExtras(bundle);
            startActivity(intent);

        }
    };
    private deletedCityListClick demelteClick = new deletedCityListClick() {
        @Override
        public void onclickManager(int position, View view) {
            Log.d("sander","删除");

            showAlertView(position);

//            deletedCity(position);
        }
    };


    private class AdressAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return homeList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            adressItem item = null;
            if (convertView == null){
                LayoutInflater infalter = getLayoutInflater();

                convertView = infalter.inflate(R.layout.adressitem, parent, false);
                TextView textView = (TextView) convertView.findViewById(R.id.adress_textview);
//                textView.setText();
                item = new adressItem(textView);
                item.ruzhuMbutton = (Button)convertView.findViewById(R.id.ruzhurenmanager);
                item.zukeMButton = (Button) convertView.findViewById(R.id.zhukemanager);
                item.deleteButton = (Button)convertView.findViewById(R.id.deletedation);
                item.adressStatus = (TextView)convertView.findViewById(R.id.addressstatus);
                convertView.setTag(item);
            }else{
                item = (adressItem) convertView.getTag();
            }
            SwipeMenuLayout swipeMenuLayout =(SwipeMenuLayout) convertView.findViewById(R.id.swipeMenulayout);
            swipeMenuLayout.smoothClose();

            ResponseHomeGetUserHomeListData data  = homeList.get(position);

            ViewGroup.LayoutParams params = convertView.getLayoutParams();

            item.adress.setText(data.getAdress());
            item.zukeMButton.setVisibility(View.GONE);
            item.ruzhuMbutton.setVisibility(View.GONE);
            params.height = DensityUtil.dip2px(getApplicationContext(),60);
            item.adressStatus.setVisibility(View.VISIBLE);

            if (data.status == 0){
                item.adressStatus.setText("待审核");
            }else if (data.status == 2){
                item.adressStatus.setText("审核没有通过");
            }else {
                // 如果审核通过了，判断用户的个人信息，来决定显示的信息
                if (data.type == 1){
                    //业主
                    item.zukeMButton.setVisibility(View.VISIBLE);
                    item.ruzhuMbutton.setVisibility(View.VISIBLE);
                    params.height = DensityUtil.dip2px(getApplicationContext(),90);
                }else if (data.type == 2){
                    //租客
                    item.ruzhuMbutton.setVisibility(View.VISIBLE);
                    params.height = DensityUtil.dip2px(getApplicationContext(),90);
                }else{
                    //其他的就是住户了.
                }
                item.adressStatus.setVisibility(View.GONE);
//                if (data.type == 2){
//                    item.zukeMButton.setVisibility(View.GONE);
//                }
            }

            convertView.setLayoutParams(params);

            item.ruzhuMbutton.setOnClickListener(mlistener);
            item.ruzhuMbutton.setTag(position);

            item.zukeMButton.setOnClickListener(managerClick);
            item.zukeMButton.setTag(position);

            item.deleteButton.setOnClickListener(demelteClick);
            item.deleteButton.setTag(position);

            return convertView;
        }


    }
    private class adressItem {
        TextView adress;
        Button ruzhuMbutton;
        Button zukeMButton;

        Button deleteButton;
        TextView adressStatus;
        public adressItem(TextView textView){
            this.adress = textView;
        }
    }

    public static abstract class adressClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            onClickAdress((Integer) v.getTag(),v);
        }
        public abstract void onClickAdress(int position, View view);
    }

    public static abstract class zhukeManagerClick implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            onclickManager((Integer)v.getTag(),v);
        }
        public abstract void onclickManager(int  position, View view);
    }
    public static abstract class deletedCityListClick implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            onclickManager((Integer)v.getTag(),v);
        }
        public abstract void onclickManager(int  position, View view);
    }
}

